﻿using MusicExplorer.Common;
using MusicExplorer.Model;
using MusicExplorer.Repository;
using MusicExplorer.Repository.Interfaces;
using MusicExplorer.ViewModel.Wrappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MusicExplorer.ViewModel
{
    public sealed class TracksPageViewModel : PageViewModelBase
    {
        private Model.Repository m_repository;
        private Entity m_filterEntity;

        private List<TrackWrapper> m_tracks;
        public List<TrackWrapper> Tracks { get { return m_tracks; } }

        public TracksPageViewModel(PageViewModelBase parent)
            : base(parent)
        {
        }

        public override string Title
        {
            get
            {
                try
                {
                    return ((IEntityFriendlyName)m_filterEntity).DisplayName;
                }
                catch
                {
                    throw new Exception("L'entité n'a pas de titre défini.");
                }
            }
        }

        protected override async Task InitializeAsync(NavigationObject obj)
        {
            m_filterEntity = obj.Entity;
            m_repository = obj.Repository;

            var classRepository = RepositoryBase.GetInstance(m_repository.ClassName);

            // Step 1 : Initialiser les tracks
            if (m_filterEntity is Genre)
            {
                var genre = (Genre)m_filterEntity;
                if(classRepository is ITracksByGenre)
                {
                    var genreRepository = (ITracksByGenre)classRepository;

                    m_tracks = new List<TrackWrapper>();

                    var tracks = await genreRepository.GetTracksByGenre(genre.Id, 1);
                    //var source = await RepositoryHelper.GetLocalSourceAsync(
                    //    string.Format("ms-appx:///Data/{0}/{0}_searchtracks.htm", m_repository.Id));
                    //var tracks = await classRepository.DecodeTracks(source);
                    foreach (var track in tracks)
                        m_tracks.Add(new TrackWrapper(this, track));
                }
            }
        }

        private string m_currentTrackPlayed;
        public string CurrentTrackPlayed
        {
            get { return m_currentTrackPlayed; }
            set
            {
                if(m_currentTrackPlayed != value)
                {
                    m_currentTrackPlayed = value;
                    RaisePropertyChanged();
                }
            }
        }
    }
}
